package org.nutz.boot.starter.h2;

import org.nutz.boot.annotation.PropDoc;
import org.nutz.boot.starter.WebServletFace;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;

import javax.servlet.Servlet;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

@IocBean
public class H2ConsoleStarter implements WebServletFace {

    protected static final String PRE = "h2.";

    @PropDoc(group = "h2", type = "boolean", defaultValue = "true", value = "是否启动h2-console")
    public static final String PROP_ENABLE = PRE + "enable";

    @PropDoc(group = "h2", type = "String", defaultValue = "/h2/*", value = "h2 控制台路径")
    public static final String PROP_PATH = PRE + "path";

    @PropDoc(group = "h2", type = "boolean", defaultValue = "true", value = "允许其他访问")
    public static final String PROP_WEB_ALLOW_OTHERS = PRE + "webAllowOthers";

    @PropDoc(group = "h2", type = "boolean", defaultValue = "false", value = "是否trace")
    public static final String PROP_TRACE = PRE + "trace";

    @Inject
    protected PropertiesProxy conf;

    @Override
    public String getName() {
        return "h2";
    }

    @Override
    public String getPathSpec() {
        return conf.get(PROP_PATH, "/h2/*");
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public Map<String, String> getInitParameters() {

        Map<String, String> params = new HashMap<>();

        if (conf.getBoolean(PROP_WEB_ALLOW_OTHERS, true)) {
            params.put("webAllowOthers", "");
        }

        if (conf.getBoolean(PROP_TRACE, false)) {
            params.put("trace", "");
        }


        Map<String, Object> map = Lang.filter((Map) conf.toMap(), "h2.", null, null, null);
        for (Entry<String, Object> en : map.entrySet()) {
            params.put(en.getKey(), String.valueOf(en.getValue()));
        }
        return params;
    }

    @Override
    public Servlet getServlet() {
        if (!conf.getBoolean(PROP_ENABLE, true)) {
            return null;
        }

        return new org.h2.server.web.WebServlet();
    }

}
